package com.cheng.reggie.service.impl;

import com.cheng.reggie.entity.ShoppingCart;
import com.cheng.reggie.mapper.ShoppingCartMapper;
import com.cheng.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;


    /**
     * 减少修改购物车数量
     *
     * @param shoppingCart
     * @return boolean
     */
    @Override
    public ShoppingCart update(ShoppingCart shoppingCart) {


    //        //查询菜品加入购物车是否大于1,大于删除
    //        ShoppingCart dbShoppingCart = shoppingCartMapper.findByShoppingCart(shoppingCart);
    //        if (dbShoppingCart.getNumber() >1) {
    //            dbShoppingCart.setNumber(dbShoppingCart.getNumber()-1);
    //            shoppingCartMapper.updateShoppingCart(shoppingCart);
    //
    //        }else{
    //            shoppingCart.setNumber(dbShoppingCart.getNumber()-1);
    //            shoppingCartMapper.deleteShoppingCart(shoppingCart);
    //
    //        }

     //   return dbShoppingCart;
        ShoppingCart dbShoppingCart = shoppingCartMapper.findByShoppingCart(shoppingCart);
        if (dbShoppingCart.getNumber() > 1) {
            shoppingCart.setNumber(dbShoppingCart.getNumber() - 1);
            shoppingCartMapper.updateShoppingCart(shoppingCart);
        }else{
            shoppingCartMapper.deleteShoppingCart(shoppingCart);
        }
        return shoppingCart;
    }

    /**
     * 添加购物车方法
     *
     * @param shoppingCart 前端传来的购物车数据
     * @return ShoppingCart 返回添加成功后购物车数据
     */
    @Override
    public ShoppingCart addCart(ShoppingCart shoppingCart) {
        //1.判断'当前加入的菜品或者套餐在当前用户购物车数据记录是否有这个数据
        ShoppingCart dbShoppingCart = shoppingCartMapper.findByShoppingCart(shoppingCart);
        if (dbShoppingCart != null) {
            //如果有数据,数量+1,调用mapper更新数据
            dbShoppingCart.setNumber(dbShoppingCart.getNumber()+1);
            shoppingCartMapper.updateNumber(dbShoppingCart.getId(), dbShoppingCart.getNumber());
        }else {
            //不存在 ,调用新增一条购物车数据记录数据
            //完善数据
             dbShoppingCart = shoppingCart;
             dbShoppingCart.setCreateTime(LocalDateTime.now());
            dbShoppingCart.setNumber(1);
            //新增插入
            shoppingCartMapper.save(dbShoppingCart);
        }
        return dbShoppingCart;
    }

    /**
     * 查询指定用户购物车集合数据
     *
     * @param userId 用户id
     * @return 返回购物车集合个数
     */
    @Override
    public List<ShoppingCart> findAllByUserId(Long userId) {
        return shoppingCartMapper.findAllByUserId(userId);

    }

    /**
     * 通过用户id进行进行清空购物车
     *
     * @param userId
     */
    @Override
    public void clean(Long userId) {
        shoppingCartMapper.deleteByUserId(userId);
    }
}
